iT邦幫忙

2022 iThome 鐵人賽

DAY 8
0
自我挑戰組

30天Java由淺入深系列 第 8

Day 8 : Conditional Expressions

  • 分享至 

  • xImage
  •  

#Intro

Today we will introduce conditional expressions. We mentioned this concept in the previous chapter. In order to deal with the many complex problems that may be encountered in different programs, conditional judgment statements are very useful. Simply put, when the statement in the if condition is true, the corresponding code is executed, otherwise the judgment is exited. In this chapter, the concepts of logic and comparison operators from Day 7 will be used extensively. If you are not familiar with this part, you can go back to the previous section to review it!


#If…Else

If there are several types of conditional judgments, the simplest one is to use an If statement to summarize the conditions that the program needs to be executed.```
/* if(condition){
If the condition is True,executed the code.
} */

int temperature = 29;
if(temperature < 30){
System.out.println("The weather was cozy today."); //If(true),so print it out.
}


If you want to determine different conditions, you can also use multiple Ifs at once: ```
int grade = 88;
if(grade >= 90 && grade <= 100)
	System.out.println("You got A+.");
if(grade >= 85 && grade <= 89)
	System.out.println("You got A.");
if(grade >= 80 && grade <= 84)
	System.out.println("You got A-.");

Else

We can observe from the above code that although it can achieve the same effect as we want, once there are more conditions to be judged, the readability of the program will deteriorate. Therefore, we can use the Else statement (which is a group with If), and when its condition is judged to be False, the code in else will be executed.

/*多個if判斷改寫*/
int grade = 84;
if(grade < 90)        
{
	if(grade < 85)
		System.out.println("You got A-.");
	else
		System.out.println("You got A.");
}
else System.out.println("You got A+.");
  • Program analysis: Lines 3 and 10 form an if…else pair. If the condition on line 3 is met, the code in the block is executed; otherwise, the statements following the word else are executed. Lines 5 and 7 form an if…else pair. If the condition on line 5 is met, the code on that line is executed; otherwise, the statements following the word else are executed.

Nested Element

When the conditions for judgment are very similar, a “nested structure” can be used to reduce unnecessary judgments.

int grade = 72;
if (grade > 90 && grade <= 100) 
  System.out.println("Excellent!");
		else if (grade > 80 && grade <= 90) 
		  System.out.println("Good!");
				else 
					System.out.println("Not bad.");
  • Program analysis: Lines 2 to 7 form a nested structure. The code will be judged continuously, and if none of the above conditions are met until the last else, the code for its block will be printed.
    -> Incidentally: if…else are all grouped together, including nested structures. The else in the ''else if'' syntax is used together with the previous if. You can write your own to understand the concept better.

Ternary Operator

If...else is, in short, a short version of conditional judgment. It can replace a large section of code and is mostly used to replace simple if...else statements.

/* variable = (condition) ? (ifexpressionTrue) : (ifexpressionFalse);*/
int grade = 100;
char GPA;
GPA = (grade >= 90) ? ('A') : ('B');
System.out.println(GPA);    /*Outputs : A*/
  • Program analysis: The short version of the if…else in line 4 is preceded by a parenthesis. We can treat the judgment inside the parenthesis as if( ), and if it is true, then the content of the first parenthesis after the question mark will be stored in a variable, and if not, then it will be executed as else and the content of the second parenthesis will be stored.

#Switch

Next, we will introduce another conditional judgment, Switch. The biggest difference between Switch and if…else is that Switch covers more cases. A common application is to select the content to be executed through our own input.
The following example provides a simple song list of function options, and the function to be used is selected through our input. (The function writing part has not been introduced here, and more content will follow.)

char grade = 'B';
switch(grade) {
	case 'A' :
		System.out.println("Excellent!");
		break;
	case 'B' :
		System.out.println("Great!");
		break;
  case 'C' :
		System.out.println("Good!");
		break;
	case 'D' :
		System.out.println("Not bad.");
		break;
	case 'E' :
		System.out.println("Don't give up.");
		break;
	default : 
		System.out.println("Wrong data!!!");
		break;
}
  • Program analysis: First, we see line 2, where the content of the parentheses in switch( ) is the case that the compiler is looking for. Then, inside the switch, we can see that there are many different kinds of cases, and at the end, there is a :
  • break : indicates the end of a case. If you forget to add it, the compiler will keep executing until it encounters break.
  • default : the case that will be executed when none of the above conditions are met.

Menu :

import java.util.Scanner;

public class web {
    public static void main(String[] args){
        
        Scanner input = new Scanner(System.in);
        System.out.println("請輸入功能編號: ");
        int function;
        function = input.nextInt();

        while(true){
	        switch(function)
            {
	            case 1 :
	                System.out.println("歌手查詢");
	                break;
	            case 2 :
	                System.out.println("歌名查詢");
	                break;
	            case 3 :
	                System.out.println("更改資訊");
	                break;
	            case 4 :
	                System.out.println("隨機撥放");
	                break;
	            default :
	                System.out.println("輸入錯誤");
	                break;
	        }
        }
    }
}

/images/emoticon/emoticon12.gif


上一篇
Day 7 : Operators and Mathematical Calculations
下一篇
Day 9 : Loop
系列文
30天Java由淺入深30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言